package br.pucrs.lognplay.job;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import br.pucrs.lognplay.entity.Client;
import br.pucrs.lognplay.entity.DynamicView;
import br.pucrs.lognplay.repository.ClientRepository;
import br.pucrs.lognplay.repository.RepositoryManager;

public class CollectorJob implements Job {

	private static final Logger logger = Logger.getLogger(CollectorJob.class);

	private static final String DYNAMIC_INDEXER_JOB_NAME = "DYNAMIC_INDEXER_JOB";

	private static final String DYNAMIC_INDEXER_TRIGGER_NAME = "DYNAMIC_INDEXER_TRIGGER";

	private static final String DYNAMIC_INDEXER_GROUP_NAME = "DYNAMIC_INDEXER_GROUP";

	private static final String LOG_ROTATE_PATH = "/etc/logrotate.d/lognplay";

	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			Runtime.getRuntime().exec("sudo logrotate -f " + LOG_ROTATE_PATH);
			logger.trace("sudo logrotate -f " + LOG_ROTATE_PATH);

			RepositoryManager.beginTransaction();
			ClientRepository clientRepository = RepositoryManager.getClientRepository();
			List<Client> clients = clientRepository.listAll();
			RepositoryManager.commitTransaction();

			for (Client client : clients) {
				DynamicView dynamicView = client.getDynamicView();

				if (dynamicView != null) { // Client lognplay
					logger.trace("Process dynamicViewId: " + dynamicView.getId());

					// @formatter:off
					JobDetail dynamicIndexerJob = newJob(DynamicIndexerJob.class)
							.withIdentity(DYNAMIC_INDEXER_JOB_NAME + "#" + dynamicView.getId(), DYNAMIC_INDEXER_GROUP_NAME)
							.build();
					
					Trigger dynamicIndexerTrigger = newTrigger()
							.withIdentity(DYNAMIC_INDEXER_TRIGGER_NAME + "#" + dynamicView.getId(), DYNAMIC_INDEXER_GROUP_NAME)
							.startNow()
							.build();
					// @formatter:on

					dynamicIndexerJob.getJobDataMap().put(DynamicIndexerJob.CLIENT_ID_PARAMETER, client.getId());
					dynamicIndexerJob.getJobDataMap().put(DynamicIndexerJob.DYNAMIC_VIEW_ID_PARAMETER, dynamicView.getId());

					if (!scheduler.checkExists(dynamicIndexerJob.getKey())) {
						scheduler.scheduleJob(dynamicIndexerJob, dynamicIndexerTrigger);
					}
				}
			}
			logger.trace("sudo rm /var/log/lognplay/*");
			Runtime.getRuntime().exec("sudo rm /var/log/lognplay/*");
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
